package com.duowan.realtime.scheduled.batch.processor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author tangsicheng
 * @version 1.0
 * @since 1.0
 */
public class MapKeyFilterProcessor implements ItemProcessor<Map, Map> {

    private static final Logger logger = LoggerFactory.getLogger(MapKeyFilterProcessor.class);
    private List<String> regexKeyWord = new LinkedList<String>();
    private List<String> normalKeyWord = new LinkedList<String>();

    @Override
    public Map process(Map item) throws Exception {
        Set<String> itemKeySet = item.keySet();
        List<String> keyToRemove = new LinkedList<String>();
        for (String itemKey : itemKeySet) {
            if (matchRegxKey(itemKey)) {

                keyToRemove.add(itemKey);
                continue;
            }
            if (matchNormalKey(itemKey)) {
                keyToRemove.add(itemKey);
            }
        }
        removeAllKeys(item, keyToRemove);
        return item;
    }

    private void removeAllKeys(Map item, List<String> keyToRemoveList) {
        for (String keyToReMove : keyToRemoveList) {
            logger.info("remove key: " + keyToReMove);
            item.remove(keyToReMove);
        }
    }

    private boolean matchNormalKey(String key) {
        for (String regexKey : normalKeyWord) {
            if (key.contains(regexKey)) return true;
        }
        return false;
    }

    private boolean matchRegxKey(String key) {
        for (String regexKey : regexKeyWord) {
            if (key.matches(regexKey)) return true;
        }
        return false;
    }


    public void setRegexKeyWord(List<String> regexKeyWord) {
        this.regexKeyWord = regexKeyWord;
    }


    public void setNormalKeyWord(List<String> normalKeyWord) {
        this.normalKeyWord = normalKeyWord;
    }
}
